package com.commute.schedule;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.LinkedList;

/*
 * This class is used to Parse ics-files into a List of
 * Activities. It currently works only with LTU ics 
 * files due to some assumptions it makes. 
 */
public class Parser {

	// This main-class tests if the parser works.
//	public static void main(String[] args) {
//		// TODO Auto-generated method stub
//		Parser icp = new Parser();
//		String fileString = null;
//		try {
//			fileString = readFileAsString("/Users/hedenberg/Documents/Universitet/M7012E/BusCommuteApp/timeedit-3.ics");
//		} catch (IOException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		ArrayList<Activity> ad = icp.parseICSString(fileString);
//		for (Activity activity : ad) {
//			System.out.println(activity.name);
//			System.out.println(activity.start);
//		}
//	}
	
	private static String readFileAsString(String filePath)
		    throws java.io.IOException{
		StringBuffer fileData = new StringBuffer(1000);
		BufferedReader reader = new BufferedReader(new FileReader(filePath));
		char[] buf = new char[1024];
		int numRead=0;
		while((numRead=reader.read(buf)) != -1){
			String readData = String.valueOf(buf, 0, numRead);
			fileData.append(readData);
			buf = new char[1024];
		}
		reader.close();
		return fileData.toString();
	}
	
	public LinkedList<Activity> parseICSFile(String filePath, double lat, double lon) {
		String ICSData = null;
		try {
			ICSData = readFileAsString(filePath);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return parseICSString(ICSData, lat, lon);
	}
	
	public LinkedList<Activity> parseICSString(String ICSData, double lat, double lon) {
		LinkedList<Activity> result = new LinkedList<Activity>();			// TODO size 20?
		String[] icsLines = ICSData.split("\r\n");
		
		int index = 0;
		int beginIndex = -1;
		
		for (String item : icsLines) {
			if (item.equals("BEGIN:VEVENT")) {
				// Save as an event start line
				beginIndex = index;
			}
			if (item.equals("END:VEVENT")) {
				// Save as an event end line
				if (beginIndex >= 0) {
					// Call parseICSEventToDictionary: and add returned dictionary to event array
					result.add(parseICSEvent(icsLines, beginIndex, index, lat, lon));
					beginIndex = -1;
				}
			}
			index++;
		}
		
		return result;
	}
	
	public Activity parseICSEvent(String[] eventArray, int startIndex, int endIndex, double lat, double lon) {
		
		Date start = null;
		Date end = null;
		Dictionary<String, String> summary = null;
		
		for (int i = startIndex; i <= endIndex; i++) {
			String[] components;
			components = eventArray[i].split(":|\\;");
			if(components[0].equals("DTSTART")){
				start = parseDTSTART(components);
			} else if(components[0].equals("DTEND")){
				end = parseDTEND(components);
			} else if(components[0].equals("UID")){
				// parseUID(components)
			} else if(components[0].equals("DTSTAMP")){
				// parseDTSTAMP(components)
			} else if(components[0].equals("SUMMARY")){
				summary = parseSUMMARY(components);
			}
				
		}
		
		/*
		 * result.put("COURSE", eventSummaryLines[0]);
			result.put("ROOM", eventSummaryLines[2]);
			result.put("ACTIVITY", eventSummaryLines[4]);
			result.put("TEACHER", eventSummaryLines[3]);
			result.put("CLASS", eventSummaryLines[5]);
		 */
		String desc = summary.get("COURSE")+" "+summary.get("ACTIVITY")+" "+summary.get("ROOM");
		return new Activity(desc, summary.get("COURSE"), summary.get("ROOM"), summary.get("ACTIVITY"), summary.get("TEACHER"), start, end, lat, lon);
	}
	
	Date parseDTSTART(String[] components){
		
		String s = components[2];
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
		Date startDate = null;
		try {
			startDate = format.parse(s);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return startDate;
	}

	Date parseDTEND(String[] components){
		
		String s = components[2];
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
		Date endDate = null;
		try {
			endDate = format.parse(s);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return endDate;
	}

	String parseUID(String[] components){
		
		return components[1];
	}

	String parseDTSTAMP(String[] components){
		
		return components[1];
	}
	
	Dictionary<String, String> parseSUMMARY(String[] components){
		Dictionary<String, String> result = new Hashtable<String, String>();
		
		String input = components[1];
		String modInput = "";
		for (int i = 0; i < input.length()-1; i++) {
			String firstChar = ""+input.charAt(i);
			String secondChar = ""+input.charAt(i+1);
			if(firstChar.equals("\\") && secondChar.equals("n")){
				modInput = modInput+"m19w78sb1g6v35i20";
				i++;
			} else {
				modInput = modInput+firstChar;
			}
			
		}
		
		// Hotfix due to failure to parse "\n"
		String[] eventSummaryLines = modInput.split("m19w78sb1g6v35i20");
		
		if (eventSummaryLines.length < 6){
			result.put("COURSE", eventSummaryLines[0]);
			
		} else if (eventSummaryLines.length < 7) {
			result.put("COURSE", eventSummaryLines[0]);
			result.put("ROOM", eventSummaryLines[2]);
			result.put("ACTIVITY", eventSummaryLines[4]);
			result.put("TEACHER", eventSummaryLines[3]);
			result.put("CLASS", eventSummaryLines[5]);
			
		} else {
			result.put("COURSE", eventSummaryLines[0]);
			result.put("ROOM", eventSummaryLines[2]);
			result.put("ACTIVITY", eventSummaryLines[4]);
			result.put("TEACHER", eventSummaryLines[3]);
			result.put("CLASS", eventSummaryLines[6]);
		}
		
		return result;
	}

}
